<?php
/**
 * @brief 用户中心模块
 * @class Ucenter
 * @note  前台
 */
class YunUcenter extends IController implements userAuthorization
{
	public $layout = 'ucenter';

	public function init()
	{

	}
    public function index()
    {
    	//获取用户基本信息
		$user = Api::run('getMemberInfo',$this->user['user_id']);
		//var_dump($user);exit();

		//获取用户各项统计数据
		$statistics = Api::run('getMemberTongJi',$this->user['user_id']);

		//获取用户站内信条数
		$msgObj = new Mess($this->user['user_id']);
		$msgNum = $msgObj->needReadNum();

		//获取用户代金券
		$propIds = trim($user['prop'],',');
		$propIds = $propIds ? $propIds : 0;
		$propData= Api::run('getPropTongJi',$propIds);

		$this->setRenderData(array(
			"user"       => $user,
			"statistics" => $statistics,
			"msgNum"     => $msgNum,
			"propData"   => $propData,
		));

        $this->initPayment();
        $this->redirect('index');
    }

	//[用户头像]上传
	function user_ico_upload()
	{
		$result = array(
			'isError' => true,
		);

		if(isset($_FILES['attach']['name']) && $_FILES['attach']['name'] != '')
		{
			$photoObj = new PhotoUpload();
			$photo    = $photoObj->run();
			if($photo['attach']['img'])
			{
				$user_id   = $this->user['user_id'];
				$user_obj  = new IModel('user');
				$dataArray = array(
					'head_ico' => $photo['attach']['img'],
				);
				$user_obj->setData($dataArray);
				$where  = 'id = '.$user_id;
				$isSuss = $user_obj->update($where);

				if($isSuss !== false)
				{
					$result['isError'] = false;
					$result['data'] = $photo['attach']['img'];
					ISafe::set('head_ico',$dataArray['head_ico']);
				}
				else
				{
					$result['message'] = '上传失败';
				}
			}
			else
			{
				$result['message'] = '上传失败';
			}
		}
		else
		{
			$result['message'] = '请选择图片';
		}
		echo JSON::encode($result);
	}

	/**
	 * 用户上传图片
	 */
	public function upload_pic(){
		if(isset($_FILES['attach']['name']) && $_FILES['attach']['name'] != ''){
			$photoObj = new PhotoUpload();
			$photo    = $photoObj->run();
			if($photo['attach']['img']){
				Yun::ajaxReturn(0, '上传成功',$photo['attach']['img']);
			}else{
				Yun::ajaxReturn(1, '上传失败');
			}
		}else{
			Yun::ajaxReturn(1, '请选择图片');
		}
	}

    /**
     * @brief 我的订单列表
     */
    public function order()
    {
		$page = isset($_REQUEST['page']) ? IFilter::act($_REQUEST['page'], 'int') : 1;
		$type = isset($_REQUEST['type']) ? $_REQUEST['type'] : '全部';
		$pagesize = 5;
		//获取订单数据
		$orders = $this->getOrderList($this->user['user_id'], $page, $pagesize, $type);
//		if(!$orders){
//			Yun::ajaxReturn(1, '未查询到相关数据');
//		}
		if($orders){
			$this->countPage = ceil($orders['total'] / 5);
			$this->orders = $orders['list'];
		}
		$this->type = $type;
        $this->initPayment();
        if ( intval(IReq::get('page')) < 2 ) {//初始化
        	$this->redirect('order');
        } else {
        	echo $this->getRenderHtml('order_items');
        }
    }

	public function getOrderList($userid, $page, $pagesize, $type){
		//初始化支付方式
		$payments = $this->initPayment();
		//判断是否有退款的中的订单
		$re_query = new IQuery('refundment_doc');
		$re_query->where = "user_id = " . $userid . " and pay_status = 0 and if_del = 0";
		$re_query->fields = 'order_id';
		$re_result = $re_query->find();
		$re_result = array_column($re_result, 'order_id');
		$re_result_str = implode(',' , $re_result);
		$query = new IQuery('order');
		switch ($type){
			case 'pay':
				$query->where = "user_id =".$userid." and if_del= 0 and status = 1";
				break;
			case 'delivery':
				if($re_result){
					$query->where = "user_id =".$userid." and if_del= 0 and status = 2 and distribution_status = 0 and id not in ({$re_result_str})";
				}else{
					$query->where = "user_id =".$userid." and if_del= 0 and status = 2 and distribution_status = 0";
				}
				break;
			case 'receipt':
				if($re_result){
					$query->where = "user_id =".$userid." and if_del= 0 and status = 2 and distribution_status = 1 and id not in ({$re_result_str})";
				}else{
					$query->where = "user_id =".$userid." and if_del= 0 and status = 2 and distribution_status = 1";
				}
				break;
			case 'finished':
				if($re_result_str){
					$query->where = "user_id =".$userid." and if_del= 0 and id in ({$re_result_str})";
				}else{
					return array();
				}
				break;
			default:
				$query->where = "user_id =".$userid." and if_del= 0";
				break;
		}
		$query->order = "id desc";
		$total = count($query->find());
		$query->page  = $page;
		$query->pagesize = $pagesize;
		$orders = $query->find();
		if ($orders){
			$order_goods_q = new IQuery('order_goods');
			$seller_model = new IModel('seller');
			foreach ($orders as &$order){
				$seller_data = $seller_model->getObj('id = ' . $order['seller_id']);
				$order['seller_name'] = $seller_data['true_name'];
				$order['status_name'] = Order_Class::orderStatusText(Order_Class::getOrderStatus($order));
				$order['pay_type_name'] = $payments[$order['pay_type']]['name'];
				$order_goods_q->where = "order_id=".$order['id'];
				$goods = $order_goods_q->find();
				$order['goods_data'] = array();
				foreach ($goods as &$good){
					$goods_json = json_decode($good['goods_array'], TRUE);
					$order['goods_data'][] = array('name' => $goods_json['name'], 'img' => $good['img'], 'real_price' => $good['real_price']);
				}
				$order['head_ico'] = $this->user['head_ico'];
			}
			return array('list' => $orders, 'total' => $total);
		}else{
			return array();
		}
	}
    /**
     * @brief 初始化支付方式
     */
    private function initPayment()
    {
        $payment = new IQuery('payment');
        $payment->fields = 'id,name,type';
        $payments = $payment->find();
        $items = array();
        foreach($payments as $pay)
        {
            $items[$pay['id']]['name'] = $pay['name'];
            $items[$pay['id']]['type'] = $pay['type'];
        }
        $this->payments = $items;
    }
    /**
     * @brief 订单详情
     * @return String
     */
    public function order_detail()
    {
        $id = IFilter::act(IReq::get('id'),'int');
		$status_name = IFilter::act(IReq::get('status_name'));
		if($status_name == '申请退款' || $status_name == '已退款'){
			return false;
		}
		$this->status_name = $status_name;
        $orderObj = new order_class();
        $this->order_info = $orderObj->getOrderShow($id,$this->user['user_id']);

        if(!$this->order_info)
        {
        	yun::ajaxReturn(1,'订单信息不存在');
        }

        //支付环境系统自动判断
        $env = ICookie::get('env');
        switch ( $env ) {
        	case 'we':
        		$this->payment_id = 13;//见payment配置
        		break;
        	case 'app':
        		$this->payment_id = 16;//见payment配置
        		break;
        	case 'wap':
        		$this->payment_id = 16;//见payment配置
        		break;
        	default:
        		$this->payment_id = 16;//见payment配置
        		break;
        }
        
        $orderStatus = Order_Class::getOrderStatus($this->order_info);
        $this->setRenderData(array('orderStatus' => $orderStatus));
		$this->status_name = Order_Class::orderStatusText($orderStatus);
        $this->redirect('order_detail',false);
    }

	/**
	 * 退款的订单详情
	 */
	public function cancelService(){
		$id = IFilter::act($_REQUEST['id'], 'int');
		$orderObj = new order_class();
		$order_info = $orderObj->getOrderShow($id, $this->user['user_id']);
		if(!$order_info){
			Yun::ajaxReturn(1, '订单信息不存在');
		}else{
			$orderStatus = Order_Class::getOrderStatus($order_info);
			$order_info['status_name'] = Order_Class::orderStatusText($orderStatus);
			$refundDB  = new IModel('refundment_doc');
			$refundRow = $refundDB->getObj('order_no = "'.$order_info['order_no'].'" and if_del = 0');
			$order_info['refundRow'] = $refundRow;
			$order_info['prop_info'] = array();
			if($order_info['prop']){
				$prop_model= new IModel('prop');
				$prop_info = $prop_model->getObj("id = " . $order_info['prop']);
				$order_info['prop_info'] = $prop_info;
			}
			$order_goods_q = new IModel('order_goods');
			$goods = $order_goods_q->getObj("order_id=".$order_info['id']);
			$goods['goods_array'] = json_decode($goods['goods_array'], TRUE);
			$order_info['goods_data'] = $goods;
			$this->order_info = $order_info;
			$this->redirect('cancelService',false);
		}
	}

    //操作订单状态
	public function order_status()
	{
		$op    = IFilter::act(IReq::get('op'));
		$id    = IFilter::act( IReq::get('order_id'),'int' );
		$model = new IModel('order');

		switch($op)
		{
			case "cancel":
			{
				$model->setData(array('status' => 3));
				if($model->update("id = ".$id." and distribution_status = 0 and status = 1 and user_id = ".$this->user['user_id']))
				{
					order_class::resetOrderProp($id);
				}
			}
			break;

			case "confirm":
			{
				$model->setData(array('status' => 5,'completion_time' => ITime::getDateTime()));
				if($model->update("id = ".$id." and distribution_status = 1 and user_id = ".$this->user['user_id']))
				{
					$orderRow = $model->getObj('id = '.$id);

					//确认收货后进行支付
					Order_Class::updateOrderStatus($orderRow['order_no']);

		    		//增加用户评论商品机会
		    		Order_Class::addGoodsCommentChange($id);

		    		//确认收货以后直接跳转到评论页面
//		    		$this->redirect('evaluation');
				}
				Order_Class::brokerageToFromuid($id);
			}
			break;
		}
		$this->redirect('/yunucenter/order_detail/id/'.$id);
		//Yun::ajaxReturn(0, '操作成功', array(), "page.view.router.refreshPage();page.view.router.refreshPreviousPage();");
	}
    /**
     * @brief 我的地址
     */
    public function address()
    {
    	//用于选中状态
    	$chk_addrid = ICookie::get('chk_addrid');

		$query = new IQuery('address');
		$query->where = 'user_id = '.$this->user['user_id'];
		$address = $query->find();
		if($address)
		{
			//默认地址的自我修正
			Yun::fixAddressDefault($address);

			foreach($address as &$ad)
			{
				$temp = area::name($ad['province'],$ad['city'],$ad['area']);
				if(isset($temp[$ad['province']]) && isset($temp[$ad['city']]) && isset($temp[$ad['area']]))
				{
					$ad['province'] = $temp[$ad['province']];
					$ad['city']     = $temp[$ad['city']];
					$ad['area']     = $temp[$ad['area']];
				}

				if ( $ad['is_default'] == 1 ) {
					$def_id = $ad['id'];
				}
			}

			//选中状态
			if ( !$chk_addrid ) $chk_addrid = $def_id;
			$this->setRenderData(array('chk_addrid'=>$chk_addrid));
		}else{
			$address = array();
		}

		$this->address = $address;
        $this->redirect('address');
    }

	/**
	 * 编辑地址信息
	 */
	public function update_address(){
		$id = IFilter::act(IReq::get('id'),'int');
		if (isset($id)){
			$addressM = new IModel('address');
			$this->address  = $addressM->getObj("id = " . $id);
			$this->provinces = $this->get_provinces();
			$this->redirect('update_address');
		}else{
			Yun::ajaxReturn(1, '无限的地址ID参数');
		}
		
	}

	/**
	 * 新增地址信息
	 */
	public function addAdres(){
		$province = $this->get_provinces();
		$this->provinces = $province;
		$this->redirect('addAdres');
	}

    /**
     * @brief 收货地址管理
     */
	public function address_edit()
	{
		$id          = IFilter::act(IReq::get('id'),'int');
		$accept_name = IFilter::act(IReq::get('accept_name'),'name');
		$province    = IFilter::act(IReq::get('province'),'int');
		$city        = IFilter::act(IReq::get('city'),'int');
		$area        = IFilter::act(IReq::get('area'),'int');
		$address     = IFilter::act(IReq::get('address'));
		$zip         = IFilter::act(IReq::get('zip'),'zip');
		$telphone    = IFilter::act(IReq::get('telphone'),'phone');
		$mobile      = IFilter::act(IReq::get('mobile'),'mobile');
		$default     = IReq::get('is_default')!= 1 ? 0 : 1;
        $user_id     = $this->user['user_id'];
		if(!$accept_name){
			Yun::ajaxReturn(1, '请填写收货人');
		}
		if(!$mobile){
			Yun::ajaxReturn(1, '请填写手机号码');
		}
		if(!preg_match('/^1[34578]\d{9}$/', $mobile)){
			Yun::ajaxReturn(1, '手机号码格式错误');
		}
		if(!$province){
			Yun::ajaxReturn(1, '请选择省份');
		}
		if(!$city){
			Yun::ajaxReturn(1, '请选择城市');
		}
		if(!$area){
			Yun::ajaxReturn(1, '请选择区域');
		}
		if(!$address){
			Yun::ajaxReturn(1, '请填写具体地址信息');
		}

		$model = new IModel('address');
		$data  = array('user_id'=>$user_id,'accept_name'=>$accept_name,'province'=>$province,'city'=>$city,'area'=>$area,'address'=>$address,'zip'=>$zip,'telphone'=>$telphone,'mobile'=>$mobile,'is_default'=>$default);

        //如果设置为首选地址则把其余的都取消首选
        if($default==1)
        {
            $model->setData(array('is_default' => 0));
            $model->update("user_id = ".$this->user['user_id']);
        }

		$model->setData($data);

		if($id == '')
		{
			$model->add();
		}
		else
		{
			$model->update('id = '.$id);
		}
		Yun::ajaxReturn();
		//$this->redirect('address');
	}
    /**
     * @brief 收货地址删除处理
     */
	public function address_del()
	{
		$id = IFilter::act( IReq::get('chk_addrid'),'int' );
		$model = new IModel('address');
		$model->del('id = '.$id.' and user_id = '.$this->user['user_id']);
		Yun::ajaxReturn(0, '删除成功', array(), 'page.view.router.refreshPage();');
	}
    /**
     * @brief 设置默认的收货地址
     */
    public function address_default()
    {
		$id = IFilter::act($_REQUEST['chk_addrid'],'int');
		$default = 1;
		$model = new IModel('address');
		if($default == 1)
		{
			$model->setData(array('is_default' => 0));
			$model->update("user_id = ".$this->user['user_id']);
		}
		$model->setData(array('is_default' => $default));
		$bool = $model->update("id = ".$id." and user_id = ".$this->user['user_id']);
		if($bool){
			Yun::ajaxReturn(0, '设置默认地址成功', array(), 'page.view.router.refreshPage();');
		}else{
			Yun::ajaxReturn(1, '设置默认地址失败');
		}
    }

	/**
	 * 申请退款
	 */
	public function refunds_money(){
		$this->order_id = $_REQUEST['order_id'];
		$this->order_goods_id = $_REQUEST['order_goods_id'];
		$this->redirect('refunds_money');
	}
    /**
     * @brief 退款申请页面
     */
    public function refunds_update()
    {
		$order_goods_id = IFilter::act( $_REQUEST['order_goods_id'],'int' );
		$order_id       = IFilter::act( $_REQUEST['order_id'],'int' );
		$user_id        = $this->user['user_id'];
		$content        = IFilter::act($_REQUEST['content'],'text');
		if(!$content){
			Yun::ajaxReturn(1, '请输入退款理由');
		}
		$imgs           = $_REQUEST['imgs'];
		if(empty($imgs)){
			Yun::ajaxReturn(1, '必须上传图片凭证');
		}
		$order_goods_id = array($order_goods_id);
		foreach ($imgs as $k => $v){
			$content .= '<p><img src=" '.$v .' " /> </p>';
		}

        if(!$content || !$order_goods_id)
        {
			Yun::ajaxReturn(1, '请填写退款理由和选择要退款的商品');
        }

        $orderDB      = new IModel('order');
        $orderRow     = $orderDB->getObj("id = ".$order_id." and user_id = ".$user_id);
        $refundResult = Order_Class::isRefundmentApply($orderRow,$order_goods_id);

        //判断退款申请是否有效
        if($refundResult === true)
        {
			//退款单数据
    		$updateData = array(
				'order_no'       => $orderRow['order_no'],
				'order_id'       => $order_id,
				'user_id'        => $user_id,
				'time'           => ITime::getDateTime(),
				'content'        => $content,
				'seller_id'      => $orderRow['seller_id'],
				'order_goods_id' => join(",",$order_goods_id),
			);

    		//写入数据库
    		$refundsDB = new IModel('refundment_doc');
    		$refundsDB->setData($updateData);
    		$refundsDB->add();

			//Yun::ajaxReturn(0, '申请退款成功');
			$this->order();
        }
        else
        {
        	$message = $refundResult;
			Yun::ajaxReturn(1, $message);
        }
    }
    /**
     * @brief 退款申请删除
     */
    public function refunds_del()
    {
        $id = IFilter::act( IReq::get('id'),'int' );
        $model = new IModel("refundment_doc");
        $model->del("id = ".$id." and user_id = ".$this->user['user_id']);
		Yun::ajaxReturn(0, '取消售后成功', array(), "mineView.router.reloadPage(creatUrl('yunucenter/order'))");
    }
    /**
     * @brief 查看退款申请详情
     */
    public function refunds_detail()
    {
        $id = IFilter::act( IReq::get('id'),'int' );
        $refundDB = new IModel("refundment_doc");
        $refundRow = $refundDB->getObj("id = ".$id." and user_id = ".$this->user['user_id']);
        if($refundRow)
        {
        	//获取商品信息
        	$orderGoodsDB   = new IModel('order_goods');
        	$orderGoodsList = $orderGoodsDB->query("id in (".$refundRow['order_goods_id'].")");
        	if($orderGoodsList)
        	{
        		$refundRow['goods'] = $orderGoodsList;
        		$this->data = $refundRow;
        	}
        	else
        	{
	        	$this->redirect('refunds',false);
	        	Util::showMessage("没有找到要退款的商品");
        	}
        	$this->redirect('refunds_detail');
        }
        else
        {
        	$this->redirect('refunds',false);
        	Util::showMessage("退款信息不存在");
        }
    }
    /**
     * @brief 查看退款申请详情
     */
	public function refunds_edit()
	{
		$order_id = IFilter::act(IReq::get('order_id'),'int');
		if($order_id)
		{
			$orderDB  = new IModel('order');
			$orderRow = $orderDB->getObj('id = '.$order_id.' and user_id = '.$this->user['user_id']);
			if($orderRow)
			{
				$this->orderRow = $orderRow;
				$this->redirect('refunds_edit');
				return;
			}
		}
		$this->redirect('refunds');
	}

    /**
     * @brief 建议中心
     */
    public function complain_edit()
    {
		$content = IFilter::act($_REQUEST['content'],'string' );
		if(!$content){
			Yun::ajaxReturn(1, '请输入意见');
		}
		$title = mb_substr($content, 0,15);
		$imgs           = $_REQUEST['imgs'];
		if($imgs){
			foreach ($imgs as $k => $v){
				$content .= '<p><img src=" '.$v .' " /> </p>';
			}
		}
		$user_id = $this->user['user_id'];
		$model = new IModel('suggestion');
		$model->setData(array('user_id'=>$user_id,'title'=>$title,'content'=>$content,'time'=>ITime::getDateTime()));
		$id = $model->add();
		if($id){
			Yun::ajaxReturn(0, '成功', array(), "mineView.router.reloadPage(creatUrl('yunucenter/setting'))");
		}else{
			Yun::ajaxReturn(1, '失败');
		}
    }
    //站内消息
    public function message()
    {
    	$msgObj = new Mess($this->user['user_id']);
    	$msgIds = $msgObj->getAllMsgIds();
    	$msgIds = $msgIds ? $msgIds : 0;
		$this->setRenderData(array('msgIds' => $msgIds,'msgObj' => $msgObj));
    	$this->redirect('message');
    }
    /**
     * @brief 删除消息
     * @param int $id 消息ID
     */
    public function message_del()
    {
        $id = IFilter::act( IReq::get('id') ,'int' );
        $msg = new Mess($this->user['user_id']);
        $msg->delMessage($id);
        $this->redirect('message');
    }
    public function message_read()
    {
        $id = IFilter::act( IReq::get('id'),'int' );
        $msg = new Mess($this->user['user_id']);
        echo $msg->writeMessage($id,1);
    }

    //[修改密码]修改动作
    function password_edit()
    {
		$fpassword  = $_REQUEST['fpassword'];
		$password   = $_REQUEST['password'];
		if(!$fpassword){
			Yun::ajaxReturn(1, '请输入旧密码');
		}
		if(!$password){
			Yun::ajaxReturn(1, '请输入新密码');
		}

		$userObj    = new IModel('user');
		$where      = 'id = '.$this->user['user_id'];
		$userRow    = $userObj->getObj($where);

		if(!preg_match('|\w{6,32}|',$password))
		{
			Yun::ajaxReturn(1, '密码格式不正确，请重新输入');
		}

		else if(md5($fpassword) != $userRow['password'])
		{
			Yun::ajaxReturn(1, '原始密码输入错误');
		}
		else
		{
			$passwordMd5 = md5($password);
			$dataArray = array(
				'password' => $passwordMd5,
			);

			$userObj->setData($dataArray);
			$result  = $userObj->update($where);
			if($result)
			{
				ISafe::set('user_pwd',$passwordMd5);
				Yun::ajaxReturn(0, '密码修改成功');
			}
			else
			{
				Yun::ajaxReturn(1, '密码修改失败');
			}
		}
    }

    //[个人资料]展示 单页
    function info()
    {
    	$user_id = $this->user['user_id'];

    	$userObj       = new IModel('user');
    	$where         = 'id = '.$user_id;
    	$this->userRow = $userObj->getObj($where);

    	$memberObj       = new IModel('member');
    	$where           = 'user_id = '.$user_id;
    	$this->memberRow = $memberObj->getObj($where);
    	$this->redirect('info');
    }

	/**
	 * 修改昵称
	 */
	public function alias(){
		$this->redirect('alias');
	}

	/**
	 * 修改生日
	 */
	public function birthday(){
		$this->redirect('birthday');
	}

	/**
	 * 个人资料的编辑
	 */
	public function info_edit_act(){
		$user_id   = $this->user['user_id'];
		$memberObj = new IModel('member');
		$where     = 'user_id = '.$user_id;

		if(isset($_REQUEST['true_name']))
			$dataArray = array(
				'true_name' => IFilter::act( $_REQUEST['true_name'] ,'string'),
			);

		if(isset($_REQUEST['sex']))
			$dataArray = array(
				'sex' => IFilter::act( IReq::get('sex'),'int' ),
			);

		if(isset($_REQUEST['birthday']))
			$dataArray = array(
				'birthday' => date('Y-m-d', strtotime(IFilter::act(IReq::get('birthday')))),
			);
		$memberObj->setData($dataArray);
		$bool = $memberObj->update($where);
		if(isset($_REQUEST['birthday']) || isset($_REQUEST['true_name'])){
			if ($bool){
				Yun::ajaxReturn(0, '修改成功', array(), "mineView.router.reloadPage(creatUrl('yunucenter/info'))");
			}else{
				Yun::ajaxReturn(1, '修改失败');
			}
		}else{
			if ($bool){
				Yun::ajaxReturn(0, '修改成功');
			}else{
				Yun::ajaxReturn(1, '修改失败');
			}
		}
	}
	//个人账户[账户余额] 展示[单页]
    function peraccount()
	{
		$user_id   = $this->user['user_id'];

		$memberObj = new IModel('member','balance');
		$where     = 'user_id = '.$user_id;
		$this->memberRow = $memberObj->getObj($where);
		//var_dump($this->memberRow);
		$this->redirect('peraccount');

	}
    //提现页面

	function withdraw()
    {
    	$user_id   = $this->user['user_id'];

		$memberObj = new IModel('member','balance');
		$where     = 'user_id = '.$user_id;
		$this->memberRow = $memberObj->getObj($where);

    	$withdrawObj = new IQuery('withdraw');
    	$where     = ' is_del=0 and user_id = '.$user_id;
		$withdrawObj->where=$where;
		$withdrawObj->order="time desc";
        $withdrawList = $withdrawObj->find();


		$this->setRenderData(array('withdrawList'=>$withdrawList));
    	$this->redirect('withdraw');
    }
	//收入明细
	function accountdetail()
	{
		$user_id   = $this->user['user_id'];
		$borkerageObj = new IQuery('order');
		$where     = 'fromuid = '.$user_id;
		$borkerageObj->where=$where;
		$borkerageObj->order="create_time desc";
		$borkerageList =$borkerageObj->find();

		$tmp = array();
		//按月份划分
		foreach($borkerageList as $value){
			$timestamp = strtotime($value['create_time']);
			$ym = date('Ym',$timestamp);
			$Y = date('Y',$timestamp);
			$m = date('m',$timestamp);
			$tmp[$ym]['Y'] = $Y;
			$tmp[$ym]['m'] = $m;
			if ( !isset($tmp[$ym]['sum']) ) {
				$tmp[$ym]['sum']=0.00;
			}
			if($value['brokerage_status']==1) {
				$tmp[$ym]['sum'] += $value['total_brokerage'];
			}
			$tmp[$ym]['list'][] = $value;
		}
        //print_r($tmp);
		//var_dump($borkerageList);
		$this->setRenderData(array('tmp'=>$tmp));
		$this->redirect('accountdetail');
	}


	//[提现余额] 展示[单页]


	//[账户余额] 提现动作
    function withdraw_act()
    {
    	$user_id = $this->user['user_id'];
    	$amount  = IFilter::act( IReq::get('amount','post') ,'float' );
    	$message = '';

    	$dataArray = array(
    		'name'   => IFilter::act( IReq::get('name','post') ,'string'),
    		'note'   => IFilter::act( IReq::get('note','post'), 'string'),
			'amount' => $amount,
			'user_id'=> $user_id,
			'time'   => ITime::getDateTime(),
    	);

		$mixAmount = 0;
		$memberObj = new IModel('member');
		$where     = 'user_id = '.$user_id;
		$memberRow = $memberObj->getObj($where,'balance');

		//提现金额范围
		if($amount <= $mixAmount)
		{
			$message = '提现的金额必须大于'.$mixAmount.'元';
			Yun::ajaxReturn(1,$message);
		}
		else if($amount > $memberRow['balance'])
		{
			$message = '提现的金额不能大于您的帐户余额';
			Yun::ajaxReturn(1,$message);
		}
		else
		{
	    	$obj = new IModel('withdraw');
	    	$obj->setData($dataArray);
	    	$obj->add();
			$message = '申请提现成功';
			Yun::ajaxReturn(0,$message,'','page.view.router.refreshPage()');
	    	//$this->redirect('withdraw');
		}
		
			$this->memberRow = array('balance' => $memberRow['balance']);
			$this->withdrawRow = $dataArray;
			$this->redirect('withdraw',false);


    }

    //[账户余额] 提现详情
    function withdraw_detail()
    {
    	$user_id = $this->user['user_id'];

    	$id  = IFilter::act( IReq::get('id'),'int' );
    	$obj = new IModel('withdraw');
    	$where = 'id = '.$id.' and user_id = '.$user_id;
    	$this->withdrawRow = $obj->getObj($where);
		//var_dump($this->withdrawRow);
    	$this->redirect('withdraw_detail');
    }

    //[提现申请] 取消
    function withdraw_del()
    {
    	$id = IFilter::act( IReq::get('id'),'int');
    	if($id)
    	{
    		$dataArray   = array('is_del' => 1);
    		$withdrawObj = new IModel('withdraw');
    		$where = 'id = '.$id.' and user_id = '.$this->user['user_id'];
    		$withdrawObj->setData($dataArray);
    		$withdrawObj->update($where);
    	}
    	$this->redirect('withdraw');
    }

    //[余额交易记录]
    function account_log()
    {
    	$user_id   = $this->user['user_id'];

    	$memberObj = new IModel('member');
    	$where     = 'user_id = '.$user_id;
    	$this->memberRow = $memberObj->getObj($where);
    	$this->redirect('account_log');
    }

    //[收藏夹]备注信息
    function edit_summary()
    {
    	$user_id = $this->user['user_id'];

    	$id      = IFilter::act( IReq::get('id'),'int' );
    	$summary = IFilter::act( IReq::get('summary'),'string' );

    	//ajax返回结果
    	$result  = array(
    		'isError' => true,
    	);

    	if(!$id)
    	{
    		$result['message'] = '收藏夹ID值丢失';
    	}
    	else if(!$summary)
    	{
    		$result['message'] = '请填写正确的备注信息';
    	}
    	else
    	{
	    	$favoriteObj = new IModel('favorite');
	    	$where       = 'id = '.$id.' and user_id = '.$user_id;

	    	$dataArray   = array(
	    		'summary' => $summary,
	    	);

	    	$favoriteObj->setData($dataArray);
	    	$is_success = $favoriteObj->update($where);

	    	if($is_success === false)
	    	{
	    		$result['message'] = '更新信息错误';
	    	}
	    	else
	    	{
	    		$result['isError'] = false;
	    	}
    	}
    	echo JSON::encode($result);
    }

    //[收藏夹]删除
    function favorite_del()
    {
    	$user_id = $this->user['user_id'];
    	$id      = IReq::get('id');

		if(!empty($id))
		{
			$id = IFilter::act($id,'int');

			$favoriteObj = new IModel('favorite');

			if(is_array($id))
			{
				$idStr = join(',',$id);
				$where = 'user_id = '.$user_id.' and id in ('.$idStr.')';
			}
			else
			{
				$where = 'user_id = '.$user_id.' and id = '.$id;
			}

			$favoriteObj->del($where);
			$this->redirect('favorite');
		}
		else
		{
			$this->redirect('favorite',false);
			Util::showMessage('请选择要删除的数据');
		}
    }

    //[我的积分] 单页展示
    function integral()
    {
    	/*获取积分增减的记录日期时间段*/
    	$this->historyTime = IFilter::string( IReq::get('history_time','post') );
    	$defaultMonth = 3;//默认查找最近3个月内的记录

		$lastStamp    = ITime::getTime(ITime::getNow('Y-m-d')) - (3600*24*30*$defaultMonth);
		$lastTime     = ITime::getDateTime('Y-m-d',$lastStamp);

		if($this->historyTime != null && $this->historyTime != 'default')
		{
			$historyStamp = ITime::getDateTime('Y-m-d',($lastStamp - (3600*24*30*$this->historyTime)));
			$this->c_datetime = 'datetime >= "'.$historyStamp.'" and datetime < "'.$lastTime.'"';
		}
		else
		{
			$this->c_datetime = 'datetime >= "'.$lastTime.'"';
		}

    	$memberObj         = new IModel('member');
    	$where             = 'user_id = '.$this->user['user_id'];
    	$this->memberRow   = $memberObj->getObj($where,'point');
    	$this->redirect('integral',false);
    }

    //[我的积分]积分兑换代金券 动作
    function trade_ticket()
    {
    	$ticketId = IFilter::act( IReq::get('ticket_id','post'),'int' );
    	$message  = '';
    	if(intval($ticketId) == 0)
    	{
    		$message = '请选择要兑换的代金券';
    	}
    	else
    	{
    		$nowTime   = ITime::getDateTime();
    		$ticketObj = new IModel('ticket');
    		$ticketRow = $ticketObj->getObj('id = '.$ticketId.' and point > 0 and start_time <= "'.$nowTime.'" and end_time > "'.$nowTime.'"');
    		if(empty($ticketRow))
    		{
    			$message = '对不起，此代金券不能兑换';
    		}
    		else
    		{
	    		$memberObj = new IModel('member');
	    		$where     = 'user_id = '.$this->user['user_id'];
	    		$memberRow = $memberObj->getObj($where,'point');

	    		if($ticketRow['point'] > $memberRow['point'])
	    		{
	    			$message = '对不起，您的积分不足，不能兑换此类代金券';
	    		}
	    		else
	    		{
	    			//生成红包
					$dataArray = array(
						'condition' => $ticketRow['id'],
						'name'      => $ticketRow['name'],
						'card_name' => 'T'.IHash::random(8),
						'card_pwd'  => IHash::random(8),
						'value'     => $ticketRow['value'],
						'start_time'=> $ticketRow['start_time'],
						'end_time'  => $ticketRow['end_time'],
						'is_send'   => 1,
					);
					$propObj = new IModel('prop');
					$propObj->setData($dataArray);
					$insert_id = $propObj->add();

					//更新用户prop字段
					$memberArray = array('prop' => "CONCAT(IFNULL(prop,''),'{$insert_id},')");
					$memberObj->setData($memberArray);
					$result = $memberObj->update('user_id = '.$this->user["user_id"],'prop');

					//代金券成功
					if($result)
					{
						$pointConfig = array(
							'user_id' => $this->user['user_id'],
							'point'   => '-'.$ticketRow['point'],
							'log'     => '积分兑换代金券，扣除了 -'.$ticketRow['point'].'积分',
						);
						$pointObj = new Point;
						$pointObj->update($pointConfig);
					}
	    		}
    		}
    	}

    	//展示
    	if($message != '')
    	{
    		$this->integral();
    		Util::showMessage($message);
    	}
    	else
    	{
    		$this->redirect('redpacket');
    	}
    }

    /**
     * 余额付款
     * T:支付失败;
     * F:支付成功;
     */
    function payment_balance()
    {
    	$urlStr  = '';
    	$user_id = intval($this->user['user_id']);

    	$return['attach']     = IReq::get('attach');
    	$return['total_fee']  = IReq::get('total_fee');
    	$return['order_no']   = IReq::get('order_no');
    	$return['return_url'] = IReq::get('return_url');
    	$sign                 = IReq::get('sign');
    	if(stripos($return['order_no'],'recharge') !== false)
    	{
    		IError::show(403,'余额支付方式不能用于在线充值');
    	}

    	if(floatval($return['total_fee']) < 0 || $return['order_no'] == '' || $return['return_url'] == '' || $return['attach'] == '')
    	{
    		IError::show(403,'支付参数不正确');
    	}

		$paymentDB  = new IModel('payment');
		$paymentRow = $paymentDB->getObj('class_name = "balance" ');
		$pkey       = Payment::getConfigParam($paymentRow['id'],'M_PartnerKey');

    	//md5校验
    	ksort($return);
		foreach($return as $key => $val)
		{
			$urlStr .= $key.'='.urlencode($val).'&';
		}

		$encryptKey = isset(IWeb::$app->config['encryptKey']) ? IWeb::$app->config['encryptKey'] : 'yunguo';
		$urlStr .= $pkey.$encryptKey;
		if($sign != md5($urlStr))
		{
			IError::show(403,'数据校验不正确');
		}

    	$memberObj = new IModel('member');
    	$memberRow = $memberObj->getObj('user_id = '.$user_id);

    	if(empty($memberRow))
    	{
    		IError::show(403,'用户信息不存在');
    	}

    	if($memberRow['balance'] < $return['total_fee'])
    	{
    		IError::show(403,'账户余额不足');
    	}

		//检查订单状态
		$orderObj = new IModel('order');
		$orderRow = $orderObj->getObj('order_no  = "'.$return['order_no'].'" and pay_status = 0 and status = 1 and user_id = '.$user_id);
		if(!$orderRow)
		{
			IError::show(403,'订单号【'.$return['order_no'].'】已经被处理过，请查看订单状态');
		}

		//扣除余额并且记录日志
		$logObj = new AccountLog();
		$config = array(
			'user_id'  => $user_id,
			'event'    => 'pay',
			'num'      => $return['total_fee'],
			'order_no' => str_replace("_",",",$return['attach']),
		);
		$is_success = $logObj->write($config);
		if(!$is_success)
		{
			IError::show(403,$logObj->error ? $logObj->error : '用户余额更新失败');
		}

		$return['is_success'] = $is_success ? 'T' : 'F';
    	ksort($return);

    	//返还的URL地址
		$responseUrl = '';
		foreach($return as $key => $val)
		{
			$responseUrl .= $key.'='.urlencode($val).'&';
		}

		$returnUrl = urldecode($return['return_url']);
		if(stripos($returnUrl,'?') === false)
		{
			$returnJumpUrl = $returnUrl.'?'.$responseUrl;
		}
		else
		{
			$returnJumpUrl = $returnUrl.'&'.$responseUrl;
		}

		//计算要发送的md5校验
		$encryptKey = isset(IWeb::$app->config['encryptKey']) ? IWeb::$app->config['encryptKey'] : 'yunguo';
		$urlStrMD5  = md5($responseUrl.$pkey.$encryptKey);

		//拼接进返还的URL中
		$returnJumpUrl.= 'sign='.$urlStrMD5;

		//同步通知
    	header('location:'.$returnJumpUrl);
    }

    //我的代金券
    function redpacket()
    {
//		$member_info = Api::run('getMemberInfo',$this->user['user_id']);
//		$propIds     = trim($member_info['prop'],',');
//		$propIds     = $propIds ? $propIds : 0;
//		$this->setRenderData(array('propId' => $propIds));
		$member_info = Api::run('getMemberInfo', $this->user['user_id']);
		$propIds     = trim($member_info['prop'], ',');
		$propIds     = $propIds ? $propIds : 0;
		$query = new IQuery('prop');
		$query->where  = "id in(".$propIds.") and is_send = 1";
		$items = $query->find();
//		if(!$items){
//			Yun::ajaxReturn(1, '未查询到相关数据');
//		}
		$this->setRenderData(array('redpackets' => $items));
		$this->redirect('redpacket');
    }

	/**
	 * 添加实体代金券
	 */
	public function add_download_ticket(){

		$ticket_num = $_REQUEST['ticket_num'];
		$ticket_pwd = $_REQUEST['ticket_pwd'];
		if(!$ticket_num){
			Yun::ajaxReturn(1, '请输入兑换卡号');
		}
		if(!$ticket_pwd){
			Yun::ajaxReturn(1, '请输入兑换密码');
		}

		//代金券状态是否正常
		$propObj = new IModel('prop');
		$propRow = $propObj->getObj('card_name = "'.$ticket_num.'" and card_pwd = "'.$ticket_pwd.'" and type = 0 and is_userd = 0 and is_send = 1 and is_close = 0 and NOW() between start_time and end_time');
		if(!$propRow) {
			Yun::ajaxReturn(1, '代金券不可用，请确认代金券的卡号密码并且此代金券从未被使用过');
		}else{
			//代金券是否已经被领取
			$memberObj = new IModel('member');
			$isRev     = $memberObj->query('FIND_IN_SET('.$propRow['id'].',prop)');
			if($isRev) {
				Yun::ajaxReturn(1, '代金券已经被领取');
			}else{
				$memberRow = $memberObj->getObj('user_id = '.$this->user['user_id'], 'prop');
				if($memberRow['prop'] == '')
				{
					$propUpdate = ','.$propRow['id'].',';
				}
				else
				{
					$propUpdate = $memberRow['prop'].$propRow['id'].',';
				}

				$dataArray = array('prop' => $propUpdate);
				$memberObj->setData($dataArray);
				$memberObj->update('user_id = '.$this->user['user_id']);
				//Yun::ajaxReturn(0, '绑定成功', 'mainView.router.reloadPage(/index.php?controller=yunucenter&action=redpacket)');
				//修改prop表
				$propObj->setData(array('member_id' => $this->user['user_id']));
				$propObj->update('id = ' . $propRow['id']);
				$this->redpacket();
			}
		}
	}

	/**
	 * 设置页面
	 */
	public function setting(){
		$this->redirect('setting');
	}

	/**
	 * 修改密码页面
	 */
	public function password(){
		$this->redirect('password');
	}

	/**
	 * 获取所有的省份
	 */
	public function get_provinces(){
		$query = new IQuery('areas');
		$query->where = "parent_id = 0";
		$provinces = $query->find();
		return $provinces;
	}

	/**
	 * 根据省份ID获取所属城市
	 */
	public function get_citys(){
		$province_id = IFilter::act($_REQUEST['province_id'], 'int');
		$query = new IQuery('areas');
		$query->where = "parent_id = " . $province_id;
		$citys = $query->find();
		if($citys){
			Yun::ajaxReturn(0, '成功', $citys);
		}else{
			Yun::ajaxReturn(1, '未查询到相关数据');
		}
	}

	/**
	 * 根据城市获得区域
	 */
	public function get_areas(){
		$city_id = IFilter::act($_REQUEST['city_id'], 'int');
		$query = new IQuery('areas');
		$query->where = "parent_id = " . $city_id;
		$areas = $query->find();
		if($areas){
			Yun::ajaxReturn(0, '成功', $areas);
		}else{
			Yun::ajaxReturn(1, '未查询到相关数据');
		}
	}

	/**
	 * 意见反馈
	 */
	public function feedback(){
		$this->redirect('feedback');
	}

	/**
	 * 商家入驻
	 */
	public function tenants(){
		$this->redirect('tenants');
	}

	/**
	 * 执行商家入驻
	 */
	public function tenants_join(){
		$name = IFilter::act($_REQUEST['name'],'string' );
		$mobile = IFilter::act($_REQUEST['mobile']);
		$main_goods = IFilter::act($_REQUEST['main_goods']);
		if(!$name){
			Yun::ajaxReturn(1, '请输入联系人');
		}
		if(!$mobile){
			Yun::ajaxReturn(1, '请输入联系电话');
		}
		if(!preg_match('/^1[34578]\d{9}$/', $mobile)){
			Yun::ajaxReturn(1, '联系电话格式错误');
		}
			if(!$main_goods){
			Yun::ajaxReturn(1, '请输入主营产品');
		}
		$model = new IModel('seller_join');
		$model->setData(array('name' => $name, 'mobile' => $mobile,'main_goods' => $main_goods,'create_time' => time()));
		$id = $model->add();
		if($id){
			Yun::ajaxReturn(0, '成功', array(), "mineView.router.reloadPage(creatUrl('yunucenter/index'))");
		}else{
			Yun::ajaxReturn(1, '失败');
		}
	}

	/**
	 * 私人定制页面
	 */
	public function customization(){
		$this->redirect('customization');
	}

	/**
	 * 私人定制接口
	 */
	public function set_customize(){
		$name = IFilter::act($_REQUEST['name'],'string' );
		$mobile = IFilter::act($_REQUEST['mobile']);
		$content = IFilter::act($_REQUEST['content']);
		if(!$name){
			Yun::ajaxReturn(1, '请输入联系人');
		}
		if(!$mobile){
			Yun::ajaxReturn(1, '请输入联系电话');
		}
		if(!preg_match('/^1[34578]\d{9}$/', $mobile)){
			Yun::ajaxReturn(1, '联系电话格式错误');
		}
		if(!$content){
			Yun::ajaxReturn(1, '请输入具体要求');
		}
		$type = IFilter::act($_REQUEST['type']);
		$model = new IModel('customize');
		$model->setData(array('name' => $name, 'mobile' => $mobile,'content' => $content, 'type' => $type, 'create_time' => time()));
		$id = $model->add();
		if($id){
			Yun::ajaxReturn(0, '成功', array(), "mineView.router.reloadPage(creatUrl('yunucenter/index'))");
		}else{
			Yun::ajaxReturn(1, '失败');
		}
	}

	/**
	 * 快递跟踪
	 */
	public function freight(){
		$id = IFilter::act($_REQUEST['delivery_id'], 'int');
		if($id)
		{
			$tb_freight = new IQuery('delivery_doc as d');
			$tb_freight->join  = 'left join freight_company as f on f.id = d.freight_id';
			$tb_freight->where = 'd.id = '.$id;
			$tb_freight->fields= 'd.*,f.freight_type,f.freight_name';
			$freightData = $tb_freight->find();
			if($freightData)
			{
				$freightData = current($freightData);
				$order_goods_q = new IModel('order_goods');
				$goods = $order_goods_q->getObj("order_id=".$freightData['order_id']);
				$this->img = $goods['img'];
				$this->freight_name = $freightData['freight_name'];
				$this->delivery_code = $freightData['delivery_code'];
				if($freightData['freight_type'] && $freightData['delivery_code']) {
//					$freightData['delivery_code'] = '3314581337899';
					$result = freight_facade::line($freightData['freight_type'],$freightData['delivery_code']);
					if($result['result'] == 'success')
					{
						//Yun::ajaxReturn(0, '查询成功', $result['data']);
						$array = array();
						for($i=count($result['data']) -1; $i >= 0; $i--){
							$array[] = $result['data'][$i];
						}
						$this->data = $array;
					}
					else
					{
//						Yun::ajaxReturn(1, '物流接口发生错误');
						$this->message = '暂无物流信息';
					}
				}else {
//					Yun::ajaxReturn(1, '');
					$this->message = '缺少物流信息';
				}
			}
		}
		$this->redirect('freight');
	}
}